import time
import asyncio
import httpx
from typing import List
from fastapi import APIRouter, BackgroundTasks
from DataModels.database import Asset

sem = asyncio.Semaphore(5)
client = httpx.AsyncClient(
    headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.142.86 Safari/537.36",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
)


clean_router = APIRouter(prefix="/clean")


@clean_router.get("")
async def clean_asset(background_tasks: BackgroundTasks, pwd: str):
    # 通过 pwd 验证，以防止接口被攻击
    # 如果不鉴权，短时大量调用，会产生大量的数据库查询开销
    # 可能会拖垮整个系统
    if pwd != "zaiwen_clean":
        return {"error": "pwd error"}
    last_week = int(time.time()) - 7 * 24 * 60 * 60

    old_assets = await Asset.find(
        Asset.created < last_week, Asset.owner == "anonymous", limit=30
    ).to_list()

    will_be_deleted_id = []
    for asset in old_assets:
        will_be_deleted_id.append(asset.id)

    if len(will_be_deleted_id) == 0:
        return will_be_deleted_id

    # await create_tasks(will_be_deleted_id)
    background_tasks.add_task(create_tasks, will_be_deleted_id)

    return will_be_deleted_id


async def create_tasks(ids: List[str]):
    tasks = []
    for index, id in enumerate(ids):
        tasks.append(async_delete_assets(id, index))

    await asyncio.gather(*tasks)


async def async_delete_assets(id: str, index: int, sem: asyncio.Semaphore = sem):
    async with sem:
        url = "http://localhost:8000/asset/delete"
        try:
            response = await client.post(url, json={"id": id})
            st_code = response.json().get("status").get("code")
            print(st_code, ":::", id, ":::", index)
        except Exception as e:
            print(e)
